import React, { FC, useState, RefObject, useRef, useEffect } from 'react';
import styles from '../index.less';
import { defaultProps, componentDefaultProps } from '../constants';
import { Responsive, CoreProps, ItemCallback , Layout, WidthProvider, Layouts } from "react-grid-layout";
import { Input, Select, InputNumber, Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

interface IFormContainer {
    currentDraggableRef: RefObject<{currentDraggable: string}>,
    changeSettingVisible: (visible: boolean) => void,
    settingVisible: boolean
}
interface IState extends CoreProps {
    items: Array<any>
}

const ResponsiveGridLayout = WidthProvider(Responsive);
const { Option } = Select;
const FormContainer: FC<IFormContainer> = (props) => {
    const { currentDraggableRef, changeSettingVisible, settingVisible } = props;
    const [state, setState] = useState<IState>({
        compactType: "vertical",
        useCSSTransforms: false,
        items: []
    });

    const onDrop = (layout: Layout[], layoutItem: Layout, _event: Event) => {
    layout = layout.sort((a, b) => a.y - b.y); 
    let newItems: any[] = [];
    layout.forEach((item: any, key) => {
        console.log(item, "item")
        if (item.i === '__dropping-elem__') {
        item.i = currentDraggableRef.current.currentDraggable;
        }
        item.x = 0;
        item.y = key === 0 ? item.y : (layout[key - 1].y + layout[key - 1].h + 1);
        item.w = 1;
        item.h = item.i.startsWith('editor') ? 3 : 2;
        newItems.push(item);
    });

    setState({
        ...state,
        items: newItems,
    });
    console.log("onDrop layout: ", layout, currentDraggableRef?.current.currentDraggable);
    console.log("onDrop layoutItem: ", layoutItem, _event);
    };

    const onLayoutChange = (layout: Layout[]) => {
        // console.log("onLayoutChange layout: ", layout);
    };

    const onDragStart: ItemCallback  = (layout: Layout[], oldItem: Layout, newItem: Layout, placeholder: Layout, event: MouseEvent, element: HTMLElement) => {
        console.log("onDragStart")
        !settingVisible && changeSettingVisible(true)
    }

    return (
        <div className={styles["formContainer"]}>
            <ResponsiveGridLayout
                {...defaultProps}
                width={800}
                onDrop={onDrop}
                rowHeight={20}
                onLayoutChange={onLayoutChange}
                measureBeforeMount={false}
                useCSSTransforms={state.useCSSTransforms}
                compactType={state.compactType}
                preventCollision={!state.compactType}
                isDroppable={true}
                onDragStart={onDragStart}
                margin={[10, 10]}//使用margin的默认值
            >
                {state.items.map(({i, x, y, w, h}) => {
                    if (i.startsWith('input')) {
                        return <div key={i} className={'d-grid'} data-grid={{i, x, y, w, h}}>
                        <Input {...componentDefaultProps} style={{height: '100%'}} data-useabled-ele="on"/>
                      </div>
                    } else if (i.startsWith('inputNumber')) {
                        return <div key={i} className={"d-grid "} data-grid={{i, x, y, w, h}}>
                          <InputNumber {...componentDefaultProps} style={{height: '100%'}} data-useabled-ele="on"/>
                        </div>
                    } else if (i.startsWith('select')) {
                        return (
                            <div key={i} className={"d-grid "} data-grid={{i, x, y, w, h}}>    
                                <Select {...componentDefaultProps} style={{ width: '100%', height: '100%' }} data-useabled-ele="on">
                                    <Option>1</Option>
                                    <Option>2</Option>
                                    <Option>3</Option>
                                </Select>
                            </div>
                        )
                    } else if(i.startsWith('upload')) {
                        return (
                            <div key={i} className="d-grid gap-2 react-resizable-hide" data-grid={{i, x, y, w, h}}>    
                                <Upload {...componentDefaultProps} style={{ width: '100%', height: '100%', display: 'inline-block' }} data-useabled-ele="on">
                                    <Button style={{ lineHeight: `${20 * h + Math.max(0, h - 1) * 10}px`, height: 50, padding: '0 4px' }} icon={<UploadOutlined />}>Click to Upload</Button>
                                </Upload>
                            </div>
                        )
                    } else {
                        return (
                            <div key={i} className="d-grid gap-2 react-resizable-hide" data-grid={{i, x, y, w, h}} >
                                <Input.TextArea {...componentDefaultProps}  style={{ height: '100%' }} data-useabled-ele="on"/>
                            </div>
                        )
                    }
                })}
            </ResponsiveGridLayout>
        </div>
    )
};


export default FormContainer;